package cn.itsource.basic.interceptor;

import cn.itsource.basic.annotation.PreAuthorize;
import cn.itsource.basic.util.AjaxResult;
import cn.itsource.org.domain.Logininfo;
import cn.itsource.system.domain.Permission;
import cn.itsource.system.mapper.PermissionMapper;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component
public class MyInterceptor implements HandlerInterceptor {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("U-TOKEN");
        Object logininfo = null;

        if (token != null){
            logininfo = redisTemplate.opsForValue().get(token);
        }
        if (logininfo == null){
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("utf-8");

            PrintWriter writer = response.getWriter();      //获取响应流

            AjaxResult noLogin = AjaxResult.me().setSuccess(false).setMessage("noLogin");
            writer.write(JSON.toJSONString(noLogin));     //此处需要写出的流是,json字符串,把错误信息返回给前端
            writer.flush();
            writer.close();
            return false;
        }
        //获取用户访问的目标方法
        HandlerMethod method = (HandlerMethod)handler;
        //该方法是否有注解
        PreAuthorize methodAnnotation = method.getMethodAnnotation(PreAuthorize.class);
        if (methodAnnotation != null){
            String sn = methodAnnotation.value();
            Logininfo lf = (Logininfo)logininfo;
            List<String> sns = permissionMapper.loadPermissionSnByLoginInfoId(lf.getId());
            //判断查询出来的sn是否包含目标方法的sn
            if(!sns.contains(sn)){
                //不包含那么就表示没有权限访问
                response.setContentType("application/json;charset=utf-8");
                response.setCharacterEncoding("utf-8");
                //获取响应流
                PrintWriter writer = response.getWriter();
                //创建Ajaxresult对象
                AjaxResult noLogin = AjaxResult.me().setSuccess(false).setMessage("没有权限访问！！！");
                writer.write(JSON.toJSONString(noLogin));
                writer.flush();
                writer.close();
                return false;
            }
        }
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);
        return true;
    }
}
